package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsDisinfectMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsFileMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsDisinfect;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.service.FarmRecordsDisinfectService;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 防疫中心 -- 消毒记录
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsDisinfectServiceImpl extends ServiceMybatis<FarmRecordsDisinfect> implements FarmRecordsDisinfectService {

    @Resource
    private FarmRecordsDisinfectMapper farmRecordsDisinfectMapper;
    @Resource
    private FarmRecordsFileMapper farmRecordsFileMapper;

    @Resource
    private FarmRecordsFileService farmRecordsFileService;

    /**
     * (政府端)
     * 根据条件查询数据
     * @param pageNum
     * @param pageSize
     * @param map
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDisinfect> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmRecordsDisinfectMapper == null){
                throw new OPServerException("farmRecordsDisinfectMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsDisinfect> farmRecordsDisinfectList = farmRecordsDisinfectMapper.selectByMap(map);

            if (farmRecordsDisinfectList.size() > 0){
                this.setPicOrVideoList(farmRecordsDisinfectList);
            }

            return new PageInfo<FarmRecordsDisinfect>(farmRecordsDisinfectList);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端按照单据状态分页查询列表
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageInfo<FarmRecordsDisinfect> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null){
            map.put("status",status);
        }
        map.put("farm_id",farmId);

        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsDisinfect> farmRecordsDisinfectList = farmRecordsDisinfectMapper.selectListByStatus(map);

        if (farmRecordsDisinfectList.size() > 0) {
            this.setPicOrVideoList(farmRecordsDisinfectList);
        }

        return new PageInfo<FarmRecordsDisinfect>(farmRecordsDisinfectList);
    }

    /**
     * 设置关联信息(视频,图片)
     * @param farmRecordsDisinfectList
     */
    public void setPicOrVideoList(List<FarmRecordsDisinfect> farmRecordsDisinfectList){
        if (farmRecordsFileMapper == null){
            throw new OPServerException("farmRecordsFileMapper 为null,请检查");
        }

        List<Long> ids = farmRecordsDisinfectList.stream().map(farmRecordsDisinfect -> farmRecordsDisinfect.getId()).collect(Collectors.toList());

        List<Integer> type2List = Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode());

        Map map = Maps.newHashMap();
        map.put("relevanceIds",ids);
        map.put("listType2",type2List);
        map.put("type1",FarmRecordsFileEnum.DISINFECT.getCode());
        //查询对应的图片,视频
        List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileMapper.selectPicOrVideoListByRelevanceIds(map);

        if (farmRecordsFileList.size() > 0){
            for (FarmRecordsDisinfect farmRecordsDisinfect : farmRecordsDisinfectList){
                this.setPicOrVideoByObject(farmRecordsDisinfect,farmRecordsFileList);
            }
        }
    }

    /**
     * 放入图片 视频到对象中
     * @param farmRecordsDisinfect
     * @param farmRecordsFileList
     */
    @Override
    public FarmRecordsDisinfect setPicOrVideoByObject(FarmRecordsDisinfect farmRecordsDisinfect, List<FarmRecordsFile> farmRecordsFileList) {
        List<String> picList = null;
        List<String> videoList = null;
        for (FarmRecordsFile farmRecordsFile : farmRecordsFileList){
            if ((farmRecordsDisinfect.getId()).equals(farmRecordsFile.getRelevance_id())){
                //获取图片
                if ((FarmRecordsFileEnum.PHOTO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    picList = list;
                }
                //获取视频
                if ((FarmRecordsFileEnum.VIDEO.getCode()).equals(farmRecordsFile.getType2())){
                    JSONArray jsonArray = JSON.parseArray(farmRecordsFile.getAddress());
                    List<String> list = jsonArray.toJavaList(String.class);
                    videoList = list;
                }
            }
        }
        //设置图片
        if (picList != null && picList.size() > 0){
            farmRecordsDisinfect.setPicList(picList);
        }
        //设置视频
        if (videoList != null && videoList.size() > 0){
            farmRecordsDisinfect.setVideoList(videoList);
        }

        return farmRecordsDisinfect;
    }

    /**
     * 新建一条记录 (暂存状态下)
     * @param farmRecordsDisinfect
     * @param loginInfo
     * @param toStatus
     * @return  long 返回插入数据的id
     */
    @Override
    public Long createOne(LoginInfo loginInfo,FarmRecordsDisinfect farmRecordsDisinfect, Integer toStatus) {
        int id = 0;
        try {
            if (farmRecordsDisinfectMapper == null){
                throw new OPServerException("farmRecordsDisinfectMapper 为null,请检查");
            }
            Integer fromStatus = farmRecordsDisinfect.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "FXD";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmRecordsDisinfectMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsDisinfect.setNumber(number);

            farmRecordsDisinfect.setProvince_id(loginInfo.getProvinceId());
            farmRecordsDisinfect.setCity_id(loginInfo.getCityId());
            farmRecordsDisinfect.setRegion_id(loginInfo.getRegionId());
            farmRecordsDisinfect.setStreet_id(loginInfo.getStreetId());
            farmRecordsDisinfect.setVillage_id(loginInfo.getVillageId());

            farmRecordsDisinfect.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //todo 单据从状态到状态
            if (fromStatus == 0 && toStatus == null){
                //直接暂存
                farmRecordsDisinfectMapper.createOne(farmRecordsDisinfect);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)){
                //直接提交
                farmRecordsDisinfect.setStatus(toStatus);
                farmRecordsDisinfectMapper.createOne(farmRecordsDisinfect);
            }

            if (farmRecordsDisinfect != null && farmRecordsDisinfect.getId() != 0) {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DISINFECT.getCode(),farmRecordsDisinfect.getPicList(),farmRecordsDisinfect.getVideoList(),farmRecordsDisinfect.getId());
            }

            //todo 生成政府操作记录

            return farmRecordsDisinfect.getId();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 更新一条记录 (根据id或者number)
     * @param farmRecordsDisinfect
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @Override
    public Integer updateByIdOrNumber(FarmRecordsDisinfect farmRecordsDisinfect,Integer toStatus) {
        try {
            if (farmRecordsDisinfectMapper == null){
                throw new OPServerException("farmRecordsDisinfectMapper 为null,请检查");
            }
            farmRecordsDisinfect.setStatus(toStatus);
            farmRecordsDisinfect.setUpdated_at(new Date());
            Integer con = farmRecordsDisinfectMapper.updateByPrimaryKeySelective(farmRecordsDisinfect);

            List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileService.selectPicOrVideoListByRelevanceIds(Lists.newArrayList(farmRecordsDisinfect.getId()),FarmRecordsFileEnum.DISINFECT.getCode(),Lists.newArrayList(FarmRecordsFileEnum.PHOTO.getCode(),FarmRecordsFileEnum.VIDEO.getCode()));

            if (farmRecordsFileList.size() > 0) {
                farmRecordsFileService.updatePicOrVideoByRelevanceId(FarmRecordsFileEnum.DISINFECT.getCode(),farmRecordsDisinfect.getPicList(),farmRecordsDisinfect.getVideoList(),farmRecordsDisinfect.getId());
            } else {
                farmRecordsFileService.insertPicOrVideoByRelevanceId(FarmRecordsFileEnum.DISINFECT.getCode(),farmRecordsDisinfect.getPicList(),farmRecordsDisinfect.getVideoList(),farmRecordsDisinfect.getId());
            }

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }
}
